package com.binary.aop;

import java.io.Serializable;
import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.binary.annotations.Ehcache;

import net.sf.ehcache.Cache;
//import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * element
 * @author wangchangbo
 * 
 *
 */
//@Aspect
//@Component
public class EhcacheAspect {
	private static Cache myCache;
	private static Cache eternalCache;
	private Logger logger = LoggerFactory.getLogger(EhcacheAspect.class);
	
/*	static{
		if(myCache==null){
			myCache = CacheManager.getInstance().getCache("myCache");
		}
		if(eternalCache==null){
			eternalCache = CacheManager.getInstance().getCache("eternalCache");
		}
	}*/
//	@Pointcut("@annotation(com.binary.annotations.Ehcache)")
	public void simplePointCut(){
		
	}
	
//	@Around("simplePointCut()")      
	public Object proJointCall(ProceedingJoinPoint pjp) throws Throwable{
		String targetName = pjp.getTarget().getClass().getName();
		String methodName = pjp.getSignature().getName();
		Object[]args = pjp.getArgs();
//		logger.info("存在缓存的地方："+targetName+","+methodName+","+JSON.toJSONString(args));
		Method[] methods = pjp.getTarget().getClass().getMethods();
		Ehcache ehcache=null;
		for(Method method:methods){
			if(method.getName().equals(methodName)){
				if(method.getParameterTypes().length==args.length){
					ehcache = method.getAnnotation(Ehcache.class);
					break;
				}
			}
		}
		if(ehcache==null){
			return null;
		}
		String key = getCacheKey(targetName,methodName,args);
		Element element = null;
		if(ehcache.eternal()){
			element = eternalCache.get(key);
		}else{
			element = myCache.get(key);
		}
		Object result = null;
		if(element==null){
			if(args!=null&&args.length>0){
				result = pjp.proceed(args);
			}else{
				result = pjp.proceed();
			}
			element = new Element(key,(Serializable)result);
			if(ehcache.eternal()){
				eternalCache.put(element);
			}else{
				myCache.put(element);
			}
			logger.info("存储："+key+",value:"+JSON.toJSONString(result));
		}else{
			logger.info("获取："+JSON.toJSONString(element.getValue()));
		}
		return element.getValue();
		
	}
	private String getCacheKey(String targetName, String methodName, Object[] args) {
		StringBuilder sb = new StringBuilder();
		sb.append(targetName).append(".").append(methodName);
		if(args!=null&&args.length>0){
			for(int i=0;i<args.length;i++){
				sb.append(".").append(JSON.toJSONString(args[i]));
			}
		}
		return sb.toString();
	}
	
	
}
